import { downloadAndUploadImg } from './file-handler'
import { Tweet } from './tweet'
import axios from 'axios'

export function handleUA(tweets: Tweet[]): void {
  // 判断日卡推文
  const dailyTweets = tweets.filter(
    (tweet) => tweet.text?.includes('カード紹介') && tweet.images && tweet.images.length > 0
  )

  console.log(tweets)
  const hashList = dailyTweets.map((tweet) => tweet.hash)
  if (hashList.length === 0) {
    return
  }
  // 判断本推文是否已经存在在数据库中
  console.log('Checking Exist Tweets')
  axios
    .post('https://cardarena.site/api/ua/info/check', hashList)
    .then(async (res) => {
      const existTweetsHash: string[] = res.data
      const newTweets = dailyTweets.filter((tweet) => !existTweetsHash.includes(tweet.hash!))
      console.log(newTweets)
      for (const tweet of newTweets) {
        const cosList: string[] = []
        for (const img of tweet!['images'] ?? []) {
          const url = await downloadAndUploadImg(img)
          cosList.push(url)
        }
        tweet.cosKeys = JSON.stringify(cosList)
      }
      await axios.post('https://cardarena.site/api/ua/info/addBatch', newTweets)
      console.log('Upload completed')
    })
    .catch((err) => {
      console.log(err)
    })
}
